package com.alogic.xscript;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import com.alogic.xscript.plugins.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.alogic.xscript.doc.xml.XmlObject;
import com.alogic.xscript.log.LogInfo;
import com.alogic.metrics.Fragment;
import com.alogic.metrics.stream.MetricsCollector;
import com.alogic.metrics.stream.MetricsHandlerFactory;
import com.alogic.tracer.Tool;
import com.alogic.tracer.TraceContext;
import com.anysoft.stream.Handler;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.XmlElementProperties;
import com.alogic.xscript.util.LogicletConstants;


/**
 * 虚基类
 * 
 * @author duanyy
 * @version 1.6.5.13 [20160612 duanyy] <br>
 * - 增加Encrypt,Decrypt,Check,CheckAndSetDefault等插件 <br>
 * 
 * @version 1.6.6.1 [20160823 duanyy] <br>
 * - 增加getAsJson和setAsJson插件 <br>
 * 
 * @version 1.6.6.13 [20170109 duanyy] <br>
 * - 采用新的指标接口
 * 
 * @version 1.6.7.3 [20170118 duanyy] <br>
 * - 对tlog的开启开关进行了统一 <br>
 * 
 * @version 1.6.7.9 [20170201 duanyy] <br>
 * - 采用SLF4j日志框架输出日志 <br>
 * 
 * @version 1.6.8.4 [20170329 duanyy] <br>
 * - 增加match插件 <br>
 * 
 * @version 1.6.8.5 [20170331 duanyy] <br>
 * - 增加rem插件 <br>
 * 
 * @version 1.6.8.14 [20170509 duanyy] <br>
 * - 增加xscript的中间文档模型,以便支持多种报文协议 <br>
 * 
 * @version 1.6.9.9 [20170829 duanyy] <br>
 * - 增加Duration插件 <br>
 * 
 * @version 1.6.10.1 [20170911 duanyy] <br>
 * - 增加incr,decr指令 <br>
 * 
 * @version 1.6.11.27 [20180417 duanyy] <br>
 * - 增加xscript的函数相关的插件func-declare,func-call,func-callback <br>
 * 
 * @version 1.6.11.28 [20180420 duanyy] <br>
 * - 增加array-string和set-multi插件; <br>
 * 
 * @version 1.6.11.34 [20180606 duanyy] <br>
 * - alogic-common:增加字符串处理插件sp; <br>
 * - alogic-common:增加集合处理插件array-set; <br>
 * 
 * @version 1.6.11.36 [20180613 duanyy] <br>
 * - 增加plus,mul,div插件 <br>
 * 
 * @version 1.6.11.57 [20180828 duanyy] <br>
 * - 增加浏览器会话id的传递 <br>
 * 
 * @version 1.6.11.58 [20180829 duanyy] <br>
 * - 增加tree,tree-node,tree-output,tree-traverse指令 <br>
 * 
 * @version 1.6.12.3 [20181013 duanyy] <br>
 * - 增加doc-cache指令 <br>
 * 
 * @version 1.6.12.4 [20171029 duanyy] <br>
 * - 支持bridge机制; <br>
 * 
 * @version 1.6.12.11 [20181206 duanyy] <br>
 * - 增加validator相关插件 <br>
 * 
 * @version 1.6.12.12 [20181207 duanyy] <br>
 * - 增加while,obj-bridge-add,obj-bridge-remove等插件 <br>
 *
 * @version 1.6.12.17 [20181226 duanyy] <br>
 * - 增加url-appender插件; <br>
 *
 * @version 1.6.12.20 [20190130 duanyy] <br>
 * - alogic-common:增加strlist,strlist-group操作插件 <br>
 *
 * @version 1.6.12.27 [20190403 duanyy] <br>
 * - 增加yaml支持插件as-yaml和from-yaml <br>
 * 
 * @version 1.6.12.28 [20190407] <br>
 * - 增加常量定义类，并通过接口继承 <br>
 *
 * @version 1.6.12.49 [20191108] <br>
 * - 增加mask相关插件，包括身份证，手机，邮箱等; <br>
 *
 * @version 1.6.12.50 [20191202 duanyy] <br>
 * - 增加repeat-obj指令，用于遍历对象的子对象 <br>
 *
 * @version 1.6.12.57 [20200103] <br>
 * - 增加通用matcher插件 <br>
 *
 * @version 1.6.13.4 [20200514 duanyy] <br>
 *  - 增加插件静态注册功能 <br>
 *
 * @version 1.6.13.6 [20200629 duanyy] <br>
 * - 增加时间相关以及递归算法插件； <br>
 *
 * @version 1.6.13.7 [20200720 duanyy] <br>
 * - 增加regex-match-multi,formula-ext等插件 <br>
 *
 * @version 1.6.13.10 [20200827 duanyy] <br>
 * - 增加filter插件 <br>
 *
 * @version 1.6.13.23 [20201030 duanyy] <br>
 * - 优化xscript的日志机制  <br>
 *
 * @version  1.6.13.26 [20201114 duanyy] <br>
 * - 增加url-appender2插件 <br>
 *
 * @version 1.6.14.3 [20210322 duanyy] <br>
 * - 增加stdin,stdout等插件 <br>
 *
 * @version 1.6.14.9 [20210507 duanyy] <br>
 * - 增加cron-match插件 <br>
 *
 * @version 1.6.14.13 [2021708 duanyy] <br>
 * - 增加EnvSubstr插件 <br>
 *
 * @version 1.6.15.3 [20211112 duanyy] <br>
 * - 优化日志框架 <br>
 *
 * @version 1.6.15.4 [20211112 duanyy] <br>
 * - 优化日志框架 <br>
 */
public abstract class AbstractLogiclet implements Logiclet,MetricsCollector, LogicletConstants {

	/**
	 * a logger of log4j
	 */
	public static final Logger logger = LoggerFactory.getLogger(Logiclet.class);
	
	/**
	 * 父节点
	 */
	private Logiclet parent = null;
	
	/**
	 * xml tag
	 */
	private String xmlTag = null;	

	private boolean traceEnable = false;
	
	/**
	 * 静态注册表（全局有效）
	 */
	protected static HashMap<String,Class<? extends Logiclet>> staticModules =
			new HashMap<String,Class<? extends Logiclet>>();
	
	/**
	 * 注册表（实例有效）
	 */
	private HashMap<String,Class<? extends Logiclet>> modules =
			new HashMap<String,Class<? extends Logiclet>>();

	protected static Handler<Fragment> metricsHandler = null;
	
	static{
		staticModules.put(STMT_INCLUDE, Include.class);
		staticModules.put(STMT_SEGMENT, Segment.class);
		staticModules.put(STMT_USING, Using.class);
		staticModules.put(STMT_ASYNC, Asynchronized.class);
		staticModules.put(STMT_THROW, Throw.class);
		staticModules.put(STMT_EXCEPTION, Except.class);
		staticModules.put(STMT_FINALLY, Except.class);
		staticModules.put(STMT_TEMPLATE, Template.class);
		staticModules.put(STMT_MSG, Message.class);
		staticModules.put(STMT_LOCATION, Location.class);
		staticModules.put(STMT_SCOPE, Scope.class);
		staticModules.put(STMT_GET, Get.class);
		staticModules.put(STMT_SET, Set.class);
		staticModules.put(STMT_SET_MULTI, SetMulti.class);
		staticModules.put(STMT_SELECT, Select.class);
		staticModules.put(STMT_ENCRYPT,Encrypt.class);
		staticModules.put(STMT_DECRYPT,Decrypt.class);
		staticModules.put(STMT_CHECK,Check.class);
		staticModules.put(STMT_CHECK_AND_SET,CheckAndSetDefault.class);
		staticModules.put(STMT_REPEAT,Repeat.class);
		staticModules.put(STMT_REPEAT_OBJ,RepeatObj.class);
		staticModules.put(STMT_SWITCH, Switch.class);
		staticModules.put(STMT_FORMULA, Formula.class);
		staticModules.put(STMT_FORMULA_EXT, FormulaExt.class);
		staticModules.put(STMT_NOW,Now.class);
		staticModules.put(STMT_NOW_NANO,Now.Nano.class);
		staticModules.put(STMT_UUID,UUid.class);
		staticModules.put(STMT_CONSTANTS, Constants.class);
		staticModules.put(STMT_LOG, Log.class);
		staticModules.put(STMT_SLEEP, Sleep.class);
		staticModules.put(STMT_FOREACH, ForEach.class);
		staticModules.put(STMT_WHILE, While.class);
		staticModules.put(STMT_OBJ, Obj.class);
		staticModules.put(STMT_OBJ_BRIDGE, Obj.Bridge.class);
		staticModules.put(STMT_OBJ_BRIDGE_ADD, Obj.BridgeAdd.class);
		staticModules.put(STMT_OBJ_BRIDGE_REMOVE, Obj.BridgeRemove.class);
		staticModules.put(STMT_ARRAY, Array.class);
		staticModules.put(STMT_ARRAY_CHILD,Array.Child.class);
		staticModules.put(STMT_ARRAYITEM, ArrayItem.class);
		staticModules.put(STMT_ARRAYSTRING, ArrayString.class);
		staticModules.put(STMT_ARRAY_SET,ArraySet.class);
		staticModules.put(STMT_TRIM, Trim.class);
		staticModules.put(STMT_UPPERCASE,Uppercase.class);
		staticModules.put(STMT_LOWERCASE,Lowercase.class);
		staticModules.put(STMT_SUBSTR,Substr.class);
		staticModules.put(STMT_SETTING, FromSettings.class);
		staticModules.put(STMT_SETTING_GET, FromSettings.class);
		staticModules.put(STMT_SETTING_SET, SetSettings.class);
		staticModules.put(STMT_ENV,FromEnv.class);
		staticModules.put(STMT_GETASJSON, GetAsJson.class);
		staticModules.put(STMT_SETASJSON, SetAsJson.class);
		staticModules.put(STMT_HASH, Hash.class);
		staticModules.put(STMT_MATCH, Match.class);
		staticModules.put(STMT_MATCHER,Matcher.class);
		staticModules.put(STMT_REM,Remove.class);
		staticModules.put(STMT_DURATION,Duration.class);
		staticModules.put(STMT_INCR,Incr.class);
		staticModules.put(STMT_DECR, Decr.class);
		staticModules.put(STMT_HEX,Hex.class);
		staticModules.put(STMT_RAND, Rand.class);
		staticModules.put(STMT_IF_TRUE, IfTrue.class);
		staticModules.put(STMT_IF_FALSE, IfFalse.class);
		staticModules.put(STMT_IF_EXIST, IfExist.class);
		staticModules.put(STMT_IF_NOT_EXIST, IfNotExist.class);
		staticModules.put(STMT_IF_EQUAL, IfEqual.class);
		staticModules.put(STMT_IF_NOT_EQUAL, IfNotEqual.class);
		staticModules.put(STMT_NEW_LINE, NewLine.class);
		staticModules.put(STMT_FUNC_DECLARE,FunctionDeclare.class);
		staticModules.put(STMT_FUNC_CALL,FunctionCall.class);
		staticModules.put(STMT_FUNC_CALLBACK, FunctionCallback.class);
		staticModules.put(STMT_EVAL, Eval.class);
		staticModules.put(STMT_LOAD, Load.class);
		staticModules.put(STMT_LOCK, Locker.class);
		staticModules.put(STMT_COUNTER, Count.class);
		staticModules.put(STMT_STRING_PROCESS, StringProcess.class);
		staticModules.put(STMT_PLUS, Plus.class);
		staticModules.put(STMT_MUL, Multiply.class);
		staticModules.put(STMT_DIVIDE, Divide.class);
		staticModules.put(STMT_REGEX_MATCHER,RegexMatcher.Single.class);
		staticModules.put(STMT_REGEX_MATCHER_MULTI,RegexMatcher.Multi.class);
		staticModules.put(STMT_TREE, Tree.class);
		staticModules.put(STMT_TREE_NODE, Tree.Node.class);
		staticModules.put(STMT_TREE_OUTPUT, Tree.Output.class);
		staticModules.put(STMT_TREE_TRAVERSE, Tree.Traverse.class);
		staticModules.put(STMT_DOC_CACHE, DocCache.class);
		staticModules.put(STMT_BRIDGE, Bridge.class);
		staticModules.put(STMT_BRIDGE_SET, Bridge.Set.class);
		staticModules.put(STMT_VALIDATOR, Validate.class);
		staticModules.put(STMT_URL_APPENDER, UrlAppender.class);
		staticModules.put(STMT_URL_APPENDER2, UrlAppender2.class);
		staticModules.put(STMT_STRING_LIST, StringList.class);
		staticModules.put(STMT_STRING_LIST_GROUP, StringListGroup.class);
		staticModules.put(STMT_AS_YAML,AsYaml.class);
		staticModules.put(STMT_FROM_YAML,FromYaml.class);
		staticModules.put(STMT_MASK_REGEX,Mask.Regex.class);
		staticModules.put(STMT_MASK_IDCARD,Mask.IdCardMask.class);
		staticModules.put(STMT_MASK_EMAIL,Mask.EmailMask.class);
		staticModules.put(STMT_MASK_MOBILE, Mask.MobileMask.class);
		staticModules.put(STMT_MASK_DEFAULT, Mask.Default.class);
		staticModules.put(STMT_TT,Timestamp.class);
		staticModules.put(STMT_TT_PARSE,Timestamp.Parser.class);
		staticModules.put(STMT_TT_OFFSET,Timestamp.Offset.class);
		staticModules.put(STMT_TT_HOUR,Timestamp.Hour.class);
		staticModules.put(STMT_TT_DAY,Timestamp.Day.class);
		staticModules.put(STMT_TT_WEEK,Timestamp.Week.class);
		staticModules.put(STMT_TT_MONTH,Timestamp.Month.class);
		staticModules.put(STMT_TT_YEAR,Timestamp.Year.class);
		staticModules.put(STMT_TT_DAY_BEGIN,Timestamp.BeginOfDay.class);
		staticModules.put(STMT_TT_WEEK_BEGIN,Timestamp.BeginOfWeek.class);
		staticModules.put(STMT_TT_MONTH_BEGIN,Timestamp.BeginOfMonth.class);
		staticModules.put(STMT_TT_YEAR_BEGIN,Timestamp.BeginOfYear.class);
		staticModules.put(STMT_RECURSE,Recurse.class);
		staticModules.put(STMT_FILTER,Filter.class);
		staticModules.put(STMT_STDIN,Stdin.class);
		staticModules.put(STMT_STDOUT,Stdout.class);
		staticModules.put(STMT_CRON_MATCH,CronMatch.class);
		staticModules.put(STMT_ENVSUBSTR,EnvSubstr.class);

		metricsHandler = MetricsHandlerFactory.getClientInstance();
	}	
	
	public AbstractLogiclet(String tag,Logiclet p){
		xmlTag = tag;
		parent = p;
	}	
	
	public boolean traceEnable(){
		return traceEnable;
	}

	@Override
	public void configure(Properties p) {
		traceEnable = PropertiesConstants.getBoolean(p, "tracer.xscript.enable", traceEnable);
	}	
	
	@Override
	public void configure(Element e, Properties p) {
		Properties props = new XmlElementProperties(e,p);
		configure(props);
	}

	@Override
	public void log(LogInfo logInfo,Properties ctx){
		if (parent != null){
			parent.log(logInfo,ctx);
		}
	}

	public void log(String message,String level,Properties ctx){
		log(new LogInfo(PropertiesConstants.getString(ctx,KEY_SN,DFT_ACTIVITY),message,level),ctx);
	}

	public void log(String message,Properties ctx){
		log(message,LOG_INFO,ctx);
	}

	public void log(String message,String level,String activity){
		if (level.equals("error")){
			logger.error(message);
		}else{
			if (level.equals("warn")){
				logger.warn(message);
			}else{
				logger.info(message);
			}
		}
	}

	public void log(String message,String level){
		log(message,level,DFT_ACTIVITY);
	}

	public void log(String message){
		log(message,LOG_INFO);
	}	

	@Override
	public void report(Element xml) {
		if (xml != null){
			xml.setAttribute("module", getClass().getName());
		}
	}

	@Override
	public void report(Map<String, Object> json) {
		if (json != null){
			json.put("module", getClass().getName());
		}
	}
	
	public void execute(XsObject root,XsObject current,LogicletContext ctx,ExecuteWatcher watcher){
		long start = System.currentTimeMillis();
		boolean error = false;
		String msg = "OK";
		TraceContext tc = null;
		if (traceEnable()){
			tc = Tool.start();
		}		
		try {
			onExecute(root,current,ctx,watcher);
		}catch (Exception ex){
			error = true;
			msg = ex.getMessage();
			throw ex;
		}finally{
			if (watcher != null){
				watcher.executed(this, ctx, error,start, System.currentTimeMillis() - start);
			}
			if (traceEnable()){
				Tool.end(tc, "LOGICLET", getXmlTag(), error?"FAILED":"OK", msg);
			}			
		}
	}
	
	@SuppressWarnings("unchecked")
	protected void onExecute(XsObject root,XsObject current,final LogicletContext ctx,final ExecuteWatcher watcher){
		if (root instanceof JsonObject){
			onExecute((Map<String, Object>)root.getContent(),(Map<String, Object>)current.getContent(),ctx,watcher);
		}else{
			if (root instanceof XmlObject){
				onExecute((Element)root.getContent(),(Element)current.getContent(),ctx,watcher);
			}else{
				throw new BaseException("core.e1000",String.format("Tag %s does not support protocol %s",this.xmlTag,root.getClass().getName()));	
			}
		}
	}
	
	protected void onExecute(final Map<String, Object> root, final Map<String, Object> current,final LogicletContext ctx,final ExecuteWatcher watcher){
		throw new BaseException("core.e1000",String.format("Tag %s does not support protocol %s",this.xmlTag,root.getClass().getName()));	
	}
	
	protected void onExecute(final Element root, final Element current,final LogicletContext ctx,final ExecuteWatcher watcher){
		throw new BaseException("core.e1000",String.format("Tag %s does not support protocol %s",this.xmlTag,root.getClass().getName()));	
	}
	
	public static String getArgument(String id,String dftValue,LogicletContext ctx){
		return ctx.GetValue(id, dftValue);
	}
	
	public static long getArgument(String id,long dftValue,LogicletContext ctx){
		String value = getArgument(id,String.valueOf(dftValue),ctx);
		
		try {
			return Long.parseLong(value);
		}catch (NumberFormatException ex){
			return dftValue;
		}
	}	
	
	public static int getArgument(String id,int dftValue,LogicletContext ctx){
		String value = getArgument(id,String.valueOf(dftValue),ctx);
		
		try {
			return Integer.parseInt(value);
		}catch (NumberFormatException ex){
			return dftValue;
		}
	}
	
	public static boolean getArgument(String id,boolean dftValue,LogicletContext ctx){
		String value = getArgument(id,Boolean.toString(dftValue),ctx);
		
		try {
			return BooleanUtils.toBoolean(value);
		}catch (NumberFormatException ex){
			return dftValue;
		}
	}	
	
	public static String getArgument(String id,LogicletContext ctx){
		String value = ctx.GetValue(id, "");
		if (StringUtils.isEmpty(value)){
			throw new BaseException("clnt.e2000","Can not find parameter:" + id);
		}
		return value;
	}	
	
	@Override
	public Logiclet parent() {
		return parent;
	}

	@Override
	public boolean isExecutable() {
		return true;
	}

	@Override
	public String getXmlTag() {
		return xmlTag;
	}

	@Override
	public Logiclet createLogiclet(String xmlTag, Logiclet parent) {
		Logiclet found = onCreateLogiclet(xmlTag,parent);
		
		if (found == null){
			Logiclet p = parent();
			if (p != null){
				found = p.createLogiclet(xmlTag, parent);
			}
		}
		
		if (found == null){
			Class<? extends Logiclet> clazz = staticModules.get(xmlTag);
			if (clazz != null){
				found = createLogiclet(clazz,xmlTag,parent);
			}
		}
		return found;
	}
	
	protected Logiclet onCreateLogiclet(String xml, Logiclet p) {
		Class<? extends Logiclet> clazz = modules.get(xml);
		return clazz == null ? null : createLogiclet(clazz,xml,p);
	}

	protected Logiclet createLogiclet(Class<? extends Logiclet> clazz,String xmlTag,Logiclet parent){
		try {
			Constructor<? extends Logiclet> constructor = clazz.getConstructor(String.class,Logiclet.class);
			return constructor.newInstance(new Object[]{xmlTag,parent});
		} catch (Exception e) {
			log(String.format("[%s]Can not create segment instance:%s",xmlTag,clazz.getName()),LOG_ERROR);
			return null;
		}
	}	

	@Override
	public void registerModule(String xmltag, Class<? extends Logiclet> clazz) {
		modules.put(xmltag, clazz);
	}

	/**
	 * 注册静态module
	 * @param xmlTag xmlTag
	 * @param clazz 插件类
	 */
	public void registerStaticModule(String xmlTag,Class<? extends Logiclet> clazz){
		log(String.format("Plugin %s registered,module:%s",xmlTag,clazz.getName()));
		staticModules.put(xmlTag,clazz);
	}

	@Override
	public void registerExceptionHandler(String id, Logiclet exceptionHandler) {
		log("Exception handler is not supported,Ignored.",LOG_WARNING);
	}

	@Override
	public void registerFunction(String id,Logiclet function){
		if (parent != null){
			parent.registerFunction(id, function);
		}
	}
	
	@Override
	public Logiclet getFunction(String id){
		return parent != null ? parent.getFunction(id):null;
	}
	
	@Override
	public void metricsIncr(Fragment fragment){
		if (metricsHandler != null){
			metricsHandler.handle(fragment,System.currentTimeMillis());
		}
	}

	public DataType getType(String type){
		return StringUtils.isEmpty(type)?DataType.STRING:DataType.valueOf(type.toUpperCase());
	}

	public boolean isTypeString(String type){
		return DataType.STRING.name().equalsIgnoreCase(type);
	}

	public boolean isTypeLong(String type){
		return DataType.LONG.name().equalsIgnoreCase(type);
	}

	public boolean isTypeInteger(String type){
		return DataType.INTEGER.name().equalsIgnoreCase(type);
	}

	public boolean isTypeDouble(String type){
		return DataType.DOUBLE.name().equalsIgnoreCase(type);
	}

	public boolean isTypeFloat(String type){
		return DataType.FLOAT.name().equalsIgnoreCase(type);
	}

	public boolean isTypeBoolean(String type){
		return DataType.BOOLEAN.name().equalsIgnoreCase(type);
	}

	public long asTypeValue(String v,long dft){
		try{
			return Long.parseLong(v);
		}catch (NumberFormatException ex){
			log(String.format("%s is not a valid long value",v),LOG_ERROR);
			return dft;
		}
	}

	public int asTypeValue(String v,int dft){
		try{
			return Integer.parseInt(v);
		}catch (NumberFormatException ex){
			log(String.format("%s is not a valid int value",v),LOG_ERROR);
			return dft;
		}
	}

	public double asTypeValue(String v,double dft){
		try{
			return Double.parseDouble(v);
		}catch (NumberFormatException ex){
			log(String.format("%s is not a valid double value",v),LOG_ERROR);
			return dft;
		}
	}

	public float asTypeValue(String v,float dft){
		try{
			return Float.parseFloat(v);
		}catch (NumberFormatException ex){
			log(String.format("%s is not a valid double value",v),LOG_ERROR);
			return dft;
		}
	}

	public boolean asTypeValue(String v,boolean dft){
		return BooleanUtils.toBoolean(v);
	}
}
